package com.lgq.cfw.service.impl;

import com.lgq.cfw.bean.TableRole;
import com.lgq.cfw.bean.example.TableRoleExample;
import com.lgq.cfw.bean.example.TableRoleExample.Criteria;
import com.lgq.cfw.dao.TableRoleMapper;
import com.lgq.cfw.service.RoleService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Lin
 * @date 2019-02-08 23:31
 **/
@Service
public class RoleServiceImpl implements RoleService {

  @Autowired
  TableRoleMapper tableRoleMapper;

  /**
   * 通过id获取角色
   * @param userId id
   * @return 角色list
   */
  @Override
  public List<TableRole> getRoleById(Integer userId) {
    return tableRoleMapper.getRoleById(userId);
  }

  /**
   * 获取所有角色
   * @return 所有角色list
   */
  @Override
  public List<TableRole> getAllRole() {
    return tableRoleMapper.selectByExample(null);
  }

  /**
   * 批量单个删除
   * @param roleDeleteIdString 角色id字符串
   * @return 是否成功
   */
  @Override
  public boolean delete(String roleDeleteIdString) {
    List<Integer> roleIdList = new ArrayList<>();
    if (!roleDeleteIdString.contains("-")) {
      try {
        tableRoleMapper.deleteByPrimaryKey(Integer.parseInt(roleDeleteIdString));
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    } else {
      String[] singleRoleIdStringArray = roleDeleteIdString.split("-");
      for (String singleRoleIdString : singleRoleIdStringArray) {
        Integer singleRoleIdInteger = Integer.parseInt(singleRoleIdString);
        roleIdList.add(singleRoleIdInteger);
      }
      TableRoleExample tableRoleExample = new TableRoleExample();
      Criteria criteria = tableRoleExample.createCriteria();
      criteria.andIdIn(roleIdList);
      try {
        tableRoleMapper.deleteByExample(tableRoleExample);
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    }
  }

  /**
   * 增加角色
   * @param roleName 角色名称
   */
  @Override
  public void addRole(String roleName) {
    TableRole tableRole=new TableRole();
    tableRole.setName(roleName);
    tableRoleMapper.insertSelective(tableRole);
  }

  /**
   * 更新角色
   * @param tableRole 疯转的角色
   */
  @Override
  public void updateRoleName(TableRole tableRole) {
    tableRoleMapper.updateByPrimaryKey(tableRole);
  }
}
